/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.epsi.bowling.data.dao;

import com.epsi.bowling.data.utils.HibernateFactory;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 *
 * @author juju
 */
class AbstractData {
    protected Session session;
    protected Transaction tx;
    protected String table = "";
    
    public AbstractData(String tableName) {
      //  session = (Session) HibernateFactory.getSessionFactory();
       // tx = session.getTransaction();
        this.table= tableName;
    }
    
    public void save(Object obj) {
        try {
            session = (Session) HibernateFactory.getSessionFactory();
            session.beginTransaction();
            session.saveOrUpdate(obj);
           // tx.commit();
            session.getTransaction().commit();
            session.close();
        } catch(HibernateException ex) {
           System.err.println("saving error: " + ex.getMessage());
        }
    }
    
    public List fetchAll() {
        session = (Session) HibernateFactory.getSessionFactory();
        Query q = session.createQuery("from " + this.table);
        List objects = q.list();
        session.close();
        return objects;
    }
    
    public Object find(Object obj, Integer id) {
        session = (Session) HibernateFactory.getSessionFactory();
        Object o = (Object) session.load((Class) obj, new Integer(id)); 
        session.close();
        return o;
    }
    
    public void delete (Object o) {
        session = (Session) HibernateFactory.getSessionFactory();
        session.delete(o);
        session.beginTransaction().commit();
        session.close();
    }
}
